/**
 * 
 */
package com.java.test.audit.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java.test.audit.dto.DepositExamineInfo;
import com.java.test.audit.dto.DrawingExamineInfo;
import com.java.test.audit.dto.RemitExamineInfo;
import com.java.test.audit.mapper.DepositExamineMapper;
import com.java.test.audit.mapper.DrawingExamineInfoMapper;
import com.java.test.audit.mapper.RemitExamineMapper;
import com.java.test.audit.push.OrderExchangeWorker;
import com.java.test.audit.service.ExamineManageService;
import com.java.test.datacenter.dto.PaymentInfo;
import com.java.test.datacenter.mapper.PaymentInfoMapper;
import com.java.test.paymanage.dto.PayChannelInfo;
import com.java.test.paymanage.dto.SkAccountInfo;
import com.java.test.paymanage.mapper.SkAccountMapper;
import com.java.test.system.feesettings.entity.FundsTypeEntity;
import com.java.test.system.fundstypemanage.FundsTypeDAO;
import com.java.test.system.fundstypemanage.FundsTypeService;
import com.java.test.system.fundstypemanage.dto.CalculationAmountDTO;
import com.java.test.system.fundstypemanage.dto.FundsTypeQueryDTO;
import com.java.test.user.dto.DepositInfo;
import com.java.test.user.dto.MemberGradeInfo;
import com.java.test.user.dto.MemberSliceInfo;
import com.java.test.user.dto.PlayAccountInfo;
import com.java.test.user.dto.ReflectInfo;
import com.java.test.user.mapper.DepositMapper;
import com.java.test.user.mapper.PlayAccountMapper;
import com.java.test.user.mapper.ReflectMapper;
import com.java.test.user.service.MemberService;
import com.java.test.util.PageInfo;
import com.java.test.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 *
 */
@Service
public class ExamineManageServiceImpl implements ExamineManageService {

	@Autowired
	private DepositExamineMapper depositExamineMapper;

	@Autowired
	private DepositMapper depositMapper;

	@Autowired
	private DrawingExamineInfoMapper drawingExamineInfoMapper;

	@Autowired
	private RemitExamineMapper remitExamineMapper;

	@Autowired
	private ReflectMapper reflectMapper;

	@Autowired
	private PaymentInfoMapper paymentInfoMapper;

	@Autowired
	RedisUtil redisUtil;

	@Autowired
	PlayAccountMapper playAccountMapper;

	@Autowired
	private SkAccountMapper skAccountMapper;

	@Autowired
	MemberService memberService;

	@Autowired
	FundsTypeService fundsTypeService;

	private static String key = "LOGIN_USER_ACCOUNT_AND_UNIQUE";

	@Override
	public PageInfo<DepositExamineInfo> selectrunwaterInfoList(PageInfo<DepositExamineInfo> page) {

		DepositExamineInfo info = page.getInfo();

		int total = depositExamineMapper.selectCount(info);

		List<DepositExamineInfo> list = depositExamineMapper.selectDepositExamineList(page, info);

		page.setTotalCount(total);

		page.setList(list);

		return page;
	}

	@Override
	public int selectbankuserCount(String cards) {
		return depositExamineMapper.selectbankuserCount(cards);

	}

	@Override
	public DepositExamineInfo selectDepositExamineInfoById(int id) {

		DepositExamineInfo info = depositExamineMapper.selectDepositExamineInfoById(id);

		return info;

	}

	/**
	 * 保存存款审核
	 * 
	 * @param info
	 * @author lijie1
	 * @date 2020/7/22 0022 17:30
	 * @return int
	 */
	public int saveDeposit(DepositExamineInfo info) {
		int a = depositExamineMapper.selectDepositByOrderNumber(info.getOrderNumber());
		int i = 0;
		if (a <= 0) {
			i = depositExamineMapper.saveDeposit(info);
		}
		return i;
	}

	/**
	 * 查询订单是否存在
	 * 
	 * @param orderNumber
	 * @author lijie1
	 * @date 2020/7/22 0022 17:30
	 * @return int
	 */
	public int selectDepositByOrderNumber(String orderNumber) {

		int i = depositExamineMapper.selectDepositByOrderNumber(orderNumber);
		return i;
	}

	/**
	 * 保存提款审核
	 * 
	 * @param info
	 * @author lijie1
	 * @date 2020/7/22 0022 17:30
	 * @return int
	 */
	public int saveDrawing(DrawingExamineInfo info) {
		int i = drawingExamineInfoMapper.saveDrawing(info);
		return i;
	}

	@Override
	@Transactional
	public int updateDepositExamineInfoById(int[] ids, int type, String name, String content) {
		synchronized (this) {
			// 审核成功需要存入存款记录表
			List<DepositExamineInfo> list = depositExamineMapper.selectDepositExamineList(ids);

			if (list == null || list.size() <= 0)
				return 0;

			List<DepositInfo> dlist = new ArrayList<DepositInfo>();
			List<PlayAccountInfo> plist = new ArrayList<PlayAccountInfo>();
			list.forEach(b -> {
				DepositInfo info = new DepositInfo();
				info.setBankAccount(b.getOutbankAccount());
				info.setDepositAmount(b.getDepositAmount());
				info.setDepositChannel(b.getDepositChannelValue());
				info.setDepositChannelName(b.getDepositChannelName());
				info.setDepositTime(b.getDepositTime());
				info.setGameAccount(b.getGameAccount());
				// 审核通过1，不通过2
				info.setStatus(type == 1 ? 1 : 2);
				info.setAuditTime(LocalDateTime.now());
				info.setAuditName(name);
				info.setIncomeAccount(b.getIncomeAccount());
				info.setContent(content);
				dlist.add(info);
				if (type == 1) {
					info.setDiscountAmount(b.getDiscountAmount());
					PlayAccountInfo changeTemp = new PlayAccountInfo();
					changeTemp.setAccount(b.getGameAccount());
					changeTemp.setCurAmount(b.getDepositAmount() + b.getDiscountAmount());
					changeTemp.setCunkuan(b.getDepositAmount());
					plist.add(changeTemp);
				}

				// 反写MQ
			});
			// 添加到存款记录表
			depositMapper.plinsertdepositInfo(dlist);
			// 删除存款审核表
			depositMapper.deletedepositById(ids);
			if (plist.size() > 0) {
				playAccountMapper.updatedepositsuccessuserAmount(plist);
			}
			// 审核通过判断升级条件
			if (type == 1) {
				this.updateGradeLvl(list);
			}
			list.forEach(c -> {
				JSONObject reqjson = new JSONObject();
				JSONArray arry = new JSONArray();
				arry.add(c.getGameUniqueId());
				arry.add(type == 1 ? 0 : 1);
				arry.add(c.getOrderNumber());
				arry.add(content);

				reqjson.put("code", 1);
				reqjson.put("data", arry);
				// -- 游戏服务器状态 0:通过 1：拒绝
				try {
					System.out.println("-================================开始=================");
					System.out.println(c.getContent());
					System.out.println(c.getOrderNumber());
					System.out.println(reqjson.toJSONString());
					boolean isuccess = OrderExchangeWorker.sendChannelOrderState(c.getContent(), c.getOrderNumber(),
							reqjson.toJSONString());
					System.out.println("===============================" + isuccess);
					if (!isuccess) {
						throw new RuntimeException("XXXXXXXXXXXXXXXXXXXXXX");
					}

				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException(e.getLocalizedMessage());
				}
			});

			return 1;
		}

	}

	public int updateGradeLvl(List<DepositExamineInfo> list) {

		List<MemberSliceInfo> slist = memberService.selectMemberSliceList();
		if (slist == null || slist.size() <= 0) {
			return 0;
		}
		slist = slist.stream().sorted(Comparator.comparing(MemberSliceInfo::getCount)).collect(Collectors.toList());

		List<MemberGradeInfo> glist = memberService.selectMemberGradeList();
		if (glist == null || glist.size() <= 0) {
			return 0;
		}
		glist = glist.stream().sorted(Comparator.comparing(MemberGradeInfo::getUpLvExp)).collect(Collectors.toList());

		for (DepositExamineInfo info : list) {

			PlayAccountInfo cinfo = depositExamineMapper.selectplaycount(info.getGameUniqueId());
			if (cinfo == null) {
				continue;
			}

			CalculationAmountDTO dto1 = new CalculationAmountDTO();
			dto1.setAmount(info.getDepositAmount());
			dto1.setFoundsType(cinfo.getFoundTypeId());
			// 计算基础货币存款
			double jcdepoamount = fundsTypeService.calculationAmount(dto1);
			
			
			CalculationAmountDTO dto2 = new CalculationAmountDTO();
			dto2.setAmount(cinfo.getRecharge_amount());
			dto2.setFoundsType(cinfo.getFoundTypeId());
			double zjrechaarge = fundsTypeService.calculationAmount(dto2);
			
			int curamount = (int) (jcdepoamount + zjrechaarge);

			if (curamount <= 0)
				continue;

			// 换算 ----- 会员等级，分层
			MemberSliceInfo msinfo = null;
			MemberGradeInfo mginfo = null;

			if (curamount >= slist.get(slist.size() - 1).getCount()) {
				msinfo = slist.get(slist.size() - 1);
			} else {
				for (int i = 0; i < slist.size(); i++) {

					if (curamount < slist.get(i).getCount()) {
						msinfo = slist.get(i);
						break;
					}

				}
			}

			if (curamount >= glist.get(glist.size() - 1).getUpLvExp()) {
				mginfo = glist.get(glist.size() - 1);
			} else {
				for (int g = 0; g < glist.size(); g++) {

					if (curamount < glist.get(g).getUpLvExp()) {
						mginfo = glist.get(g);
						break;
					}
				}
			}

			PlayAccountInfo tinfo = new PlayAccountInfo();
			tinfo.setAccountName(info.getGameUniqueId());
			tinfo.setSliceValue(msinfo.getId());
			tinfo.setSliceName(msinfo.getSliceName());
			tinfo.setGradeValue(mginfo.getId());
			tinfo.setGradeName(mginfo.getMemberGradeName());
			tinfo.setRecharge_amount(info.getDepositAmount());
			playAccountMapper.updatemembergradeslice(tinfo);

		}

		return 1;
	}

	@Override
	public String getGameUniqueNumber(String gameAccount) {

		if (gameAccount == null || gameAccount.length() <= 0)
			return null;
		// 用户唯一账号
		Object obj = redisUtil.hget(key, gameAccount);

		if (obj == null || "".equals(obj.toString())) {
			// 数据库查询
			String uniqueNo = playAccountMapper.getUniqueNumber(gameAccount);

			if (uniqueNo != null && !"".equals(uniqueNo)) {
				redisUtil.hset(key, gameAccount, uniqueNo);
			}

			return uniqueNo;
		} else {
			return obj.toString();
		}
	}

	@Override
	public PageInfo<DrawingExamineInfo> selectdrawingInfoList(PageInfo<DrawingExamineInfo> page) {
		DrawingExamineInfo info = page.getInfo();

		int total = drawingExamineInfoMapper.selectCount(info);

		List<DrawingExamineInfo> list = drawingExamineInfoMapper.selectpageList(page, info);

		page.setTotalCount(total);

		page.setList(list);

		return page;
	}

	@Override
	public DrawingExamineInfo selectdrawingInfoByid(DrawingExamineInfo infos) {

		DrawingExamineInfo info = drawingExamineInfoMapper.selectExamineInfoBid(infos);

		return info;
	}

	@Override
	@Transactional
	public int updateExamineInfo(int[] ids, int type, String reviewerName, String content) {
		synchronized (this) {
			List<DrawingExamineInfo> list = drawingExamineInfoMapper.selectremitExamineList(ids);
			if (list == null || list.size() <= 0)
				return 0;
			// type:1 审核通过 2：审核不通过
			if (type == 1) {
				List<RemitExamineInfo> ilist = new ArrayList<RemitExamineInfo>();
				list.forEach(b -> {
					RemitExamineInfo info = new RemitExamineInfo();
					info.setGameAccount(b.getGameAccount());
					info.setRemitAmount(b.getDrawingAmount());
					info.setRemitChannelValue(b.getDrawingChannelValue());
					info.setRemitChannelName(b.getDrawingChannelName());
					info.setRemitbankAccount(b.getDrawbankAccount());
					info.setRemitTime(b.getDrawingTime());
					info.setAuditStatus(1);
					info.setReviewer(reviewerName);
					info.setAuditTime(LocalDateTime.now());
					info.setRemitStatus(2);
					info.setOrderNumber(b.getOrderNumber());
					info.setContent(b.getContent());
					info.setGame_unique_id(b.getGameUniqueId());
					info.setSxfCharge(b.getSxfCharge());
					info.setDzjeAmount(b.getDzjeAmount());
					ilist.add(info);
				});
				// 删除通过的，
				drawingExamineInfoMapper.deleteExmaineInfos(ids);
				// 将通过记录写入 -- 待汇款
				remitExamineMapper.insertplRemitInfo(ilist);
			} else if (type == 2) {
				List<String> gamelist = new ArrayList<String>();
				List<ReflectInfo> rlist = new ArrayList<ReflectInfo>();
				list.forEach(b -> {
					ReflectInfo info = new ReflectInfo();
					info.setGameAccount(b.getGameAccount());
					info.setBankAccount(b.getDrawbankAccount());
					info.setReflectAmount(b.getDrawingAmount());
					info.setReflectChannel(b.getDrawingChannelValue());
					info.setReflectChannelName(b.getDrawingChannelName());
					info.setReflectTime(b.getDrawingTime());
					info.setReviewer(reviewerName);
					info.setReviewTime(LocalDateTime.now());
					info.setStatus(2);
					info.setSxfCharge(b.getSxfCharge());
					info.setDzjeAmount(b.getDzjeAmount());
					gamelist.add(b.getGameAccount());
					rlist.add(info);
				});
				// 不通过写入：提现记录表
				reflectMapper.plinsertdepositInfo(rlist);
				drawingExamineInfoMapper.deleteExmaineInfos(ids);
				// 将冻结金额转入余额
				playAccountMapper.updaterefectfailduserAmount(gamelist);

			}

			// 发送游戏服务器
			list.forEach(b -> {
				JSONObject reqjson = new JSONObject();
				JSONArray arry = new JSONArray();
				arry.add(b.getGameUniqueId());
				arry.add(type == 1 ? 0 : 1);
				arry.add(b.getOrderNumber());
				arry.add(content);
				reqjson.put("code", 2);
				reqjson.put("data", arry);
				// -- 游戏服务器状态 0:通过 1：拒绝
				try {
					OrderExchangeWorker.sendChannelOrderState(b.getContent(), b.getOrderNumber(),
							reqjson.toJSONString());
				} catch (Exception e) {
					e.printStackTrace();
					throw new RuntimeException(e.getLocalizedMessage());
				}
			});

			// drawingExamineInfoMapper.updateExamineInfo(ids, type)
			return 1;
		}
	}

	@Override
	public PageInfo<RemitExamineInfo> selectremitInfoList(PageInfo<RemitExamineInfo> page) {
		RemitExamineInfo info = page.getInfo();

		int total = remitExamineMapper.selectCount(info);

		List<RemitExamineInfo> list = remitExamineMapper.selectpageList(page, info);

		page.setTotalCount(total);

		page.setList(list);

		return page;
	}

	@Override
	@Transactional
	public int updateremitExaminInfo(int id, String name) {
		synchronized (this) {
			// 存款记录
			int i = remitExamineMapper.updateremitExaminInfo(id);

			if (i > 0) {
				// 存入打款明细表
				RemitExamineInfo dinfo = remitExamineMapper.selectremitInfoById(id);
				PaymentInfo info = new PaymentInfo();
				info.setAmount(dinfo.getRemitAmount());
				info.setNewOutTime(LocalDateTime.now());
				info.setRemitId(id);
				// 需要更改
				info.setUserId(1);
				info.setUserName(name);
				paymentInfoMapper.insertPaymentInfo(info);

				// 存入提款记录表
				List<ReflectInfo> list = new ArrayList<ReflectInfo>();
				ReflectInfo rinfo = new ReflectInfo();
				rinfo.setGameAccount(dinfo.getGameAccount());
				rinfo.setBankAccount(dinfo.getRemitbankAccount());
				rinfo.setReflectAmount(dinfo.getRemitAmount());
				rinfo.setReflectChannel(dinfo.getRemitChannelValue());
				rinfo.setReflectTime(dinfo.getRemitTime());
				rinfo.setStatus(1);
				rinfo.setReviewer(dinfo.getReviewer());
				rinfo.setReflectTime(dinfo.getAuditTime());
				rinfo.setReflectChannel(dinfo.getRemitChannelValue());
				rinfo.setSxfCharge(dinfo.getSxfCharge());
				rinfo.setDzjeAmount(dinfo.getDzjeAmount());
				rinfo.setReflectChannelName(dinfo.getRemitChannelName());
				list.add(rinfo);
				reflectMapper.plinsertdepositInfo(list);

				playAccountMapper.updaterefectsuccessuserAmount(dinfo.getRemitAmount(), dinfo.getGameAccount());

				{
					// 给游戏端推送消息
					JSONObject reqjson = new JSONObject();
					JSONArray arry = new JSONArray();
					arry.add(dinfo.getGame_unique_id());
					arry.add(2);
					arry.add(dinfo.getOrderNumber());
					arry.add(String.valueOf(dinfo.getDzjeAmount()));
					reqjson.put("code", 2);
					reqjson.put("data", arry);
					// -- 游戏服务器状态 0:通过 1：拒绝
					try {
						OrderExchangeWorker.sendChannelOrderState(dinfo.getContent(), dinfo.getOrderNumber(),
								reqjson.toJSONString());
					} catch (Exception e) {
						e.printStackTrace();
						throw new RuntimeException(e.getLocalizedMessage());
					}
				}

			}

			return i;
		}
	}

	@Override
	public void dealCodeSizemethod() {

		List<DrawingExamineInfo> list = drawingExamineInfoMapper.selectalldataList();

		if (list == null || list.size() <= 0)
			return;

		list.forEach(b -> {
			// b -> 当前提款 ---- 和上一次提款做比较

			ReflectInfo info = reflectMapper.selectreflectList(b.getGameAccount());

			if (info == null) { // 第一次提款

				List<DepositInfo> isdepositlist = depositMapper.selectdepositlistcodeSize(null, null,
						b.getGameAccount());

				if (isdepositlist != null && isdepositlist.size() > 0) {
					//
					double sumamount = 0.00;

				} else {
					b.setStatus(2); // 未完成
				}
			} else {

				LocalDateTime startTime = b.getDrawingTime();

				LocalDateTime endTime = info.getReflectTime();

				// List<DepositInfo> isdepositlist =
				// depositMapper.selectdepositlistcodeSize(startTime, endTime);
			}

		});

	}

	/**
	 * 查询优惠比例
	 * 
	 * @param channelId
	 * @param payClass
	 * @param toCardId
	 * @author
	 * @date 2020/8/6 0006 10:03
	 * @return java.lang.String
	 */
	@Override
	public String selectPayManageSKAccount(String channelId, String payClass, String toCardId) {
		String yhproportion = "0";
		SkAccountInfo info = new SkAccountInfo();
		info.setChannelId(Integer.parseInt(channelId));
		info.setPayType(Integer.parseInt(payClass));
		info.setSkAccount(toCardId);
		List<SkAccountInfo> list = skAccountMapper.selectskaccount(info);
		if (list.size() > 0) {
			yhproportion = list.get(0).getYhproportion();
		}
		return yhproportion;
	}

	public static void main(String[] args) {
		double a = 0.1d;
		double b = 0.2d;
		System.out.println(a * b);
	}
}
